/**
 * 作者:hanbo
 * 日期:2018/11/1915:41
 * 描述:WMS服务图层
 */
import {Layer} from "./Layer";
import {DownImage} from "../tool/DownImage";

export class WMSLayer extends Layer{
    /**
     *
     * @param url {String} WMS服务地址
     * @param layers {String} 图层名称，多个图层中间可以用逗号隔开
     * @param transparent {Boolean} 背景是否透明
     * @param version {String} 服务版本 1.3.0,1.0.0,1.1.0,1.1.1
     * @param imgFormat {String} 请求图片格式 image/png,image/png8,image/jpeg,image/gif,image/tiff,image/tiff8,
     * @param srid {String} 坐标系srid 4326,3857
     */
    constructor(url,layers, transparent=true, version="1.1.1", imgFormat="image/png",  srid="3857"){
        super();
        this.url=url;
        this.layers=layers;
        this.transparent=transparent;
        this.version=version;
        if (this.version =="1.3.0") {
            this.coordinate = "CRS=EPSG:" + srid;
        } else {
            this.coordinate = "SRS=EPSG:" + srid;
        }
        this.imgFormat=imgFormat;
    }

    /**
     * 根据地图范围绘制
     * @param mapRender {MapRender} 渲染器
     * @param extend {Rectangle} 坐标范围
     * @param level {Number} 地图等级
     * @param layerAmount {number} 图层数量
     * @param layerIndex {number} 图层索引
     */
    draw(mapRender, extend,level,layerAmount,layerIndex){
        let pixel_per_Meter = mapRender.getPixel_per_Meter();
        let width = WMSLayer.toEvenNumber((extend.xMax - extend.xMin) *pixel_per_Meter);
        let height = WMSLayer.toEvenNumber((extend.yMax - extend.yMin) *pixel_per_Meter);
        let currentUrl = this.url + "?SERVICE=WMS&REQUEST=GetMap&VERSION=" + this.version + "&FORMAT=" + this.imgFormat
            + "&TRANSPARENT=" + this.transparent + "&STYLES&LAYERS=" + this.layers + "&" + this.coordinate + "&WIDTH=" + width
            + "&HEIGHT=" + height + "&BBOX=" + extend.xMin + "," + extend.yMin
            + "," +extend.xMax + "," + extend.yMax;
        const uuid=this.uuid;
        DownImage.downImage(currentUrl, function (image) {
            mapRender.drawImageLoad(image,extend,uuid,layerIndex/layerAmount);
        })
    }

    /**
     * 数字转为偶数
     * @param number {Number} 传入数字
     * @returns {*} 偶数
     */
    static toEvenNumber(number){
        let result=Math.ceil(number);//小数转整数
        if (result % 2 == 1) {
            return result - 1;
        }
        return result;
    }
}